import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'

//引入路由器对象
import router from '@/router'

// 引入常量路由，动态路由，任意路由
import { constantRoutes, asyncRoutes, anyRoutes } from '@/router/routes'

import cloneDeep from 'lodash/cloneDeep'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    roles: [], // 角色权限相关的数组
    asyncRoutes: [], // 异步路由数组
    routes: [] // 所有路由的相关数组
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
   // 保存用户信息
  SET_USER(state, {
    avatar,
    name,
    roles
  }) {
    state.avatar = avatar // 头像
    state.name = name // 用户名字
    state.roles = roles // 权限的数组
  },
  // 保存路由信息
  SET_ROUTES(state, asyncRoutes) {
    // 一定是合并后的(已经过滤后的动态路由的数组)
    // 存储动态路由数组数据
    state.asyncRoutes = asyncRoutes
    // 合并路由数组
    state.routes = constantRoutes.concat(asyncRoutes, anyRoutes)
    // 再把异步路由和任意路由重新加入到常量路由中,真正的在路由器中合并路由数据
    router.addRoutes([...asyncRoutes, anyRoutes])
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password }).then(response => {
        localStorage.setItem('token', response.data.token);
        const { data } = response
        commit('SET_TOKEN', data.token)
        setToken(data.token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo().then(response => {
        const { data } = response

        if (!data) {
          return reject('Verification failed, please Login again.')
        }

        const { name, avatar } = data

        // 保存用户信息
        commit('SET_USER', data);
        // 加工路由对象
        const resultRoutes = filterAsyncRoutes(cloneDeep(asyncRoutes), data.routes);
        // 保存路由信息
        commit('SET_ROUTES', resultRoutes);

        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        localStorage.removeItem('token');
        removeToken() // must remove  token  first
        resetRouter()
        commit('RESET_STATE')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}


// 过滤路由对象信息数据的函数
function filterAsyncRoutes (routes, routeNames) {
  return routes.filter(route => {
    // 当前的路由对象的名字是否在路由名字数组中存在
    if (routeNames.includes(route.name)) {
      // 当前的路由对象中有没有子路由
      if (route.children && route.children.length > 0) {
        // 子路由中是否还有子路由对象
        const cRoute = filterAsyncRoutes(route.children, routeNames)
        // 判断子路由是否真的存在
        if (cRoute && cRoute.length > 0) {
          // 存储子路由
          route.children = cRoute
          return true
        }
        return false
      }
      return true
    }
    return false
  })
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

